import {getToken} from "@/utils/auth";
var lockReconnect = false;//避免重复连接
const socketUtil = {
    reconnectInterval : 60 * 1000 ,//重试间隔
    reconnectTimeOuter: null ,//重试间隔
    wsClient: null //ws对象
}

import useTestResultStore from '@/store/modules/testResult'
const connectSocket = {}
/**
 * @description 创建实例并
 * @param {*} topic topic
 * @returns websocket实例
 */
socketUtil.connect = (topic) => {
    const baseIp = window.location.host
    const baseUrl = import.meta.env.VITE_APP_WS_BASE_URL
    const wsUrl = `ws://${baseIp}${baseUrl}/${topic}`
    if (socketUtil.wsClient) {
        console.log(socketUtil.wsClient);
        return socketUtil.wsClient
    } else {
        socketUtil.wsClient = new WebSocket(wsUrl)
        console.log(socketUtil.wsClient);
    }
    return socketUtil.wsClient

}


socketUtil.init  = function () {
    //建立websocket
    socketUtil.wsClient = null
    let wsClient =  socketUtil.connect('/ws'+getToken() )
    console.log("建立socket")
    wsClient.onopen = () => {
        console.log("建立socket成功")
        socketUtil.reconnectTimeOuter && clearInterval(socketUtil.reconnectTimeOuter)
        socketUtil.reconnectTimeOuter = setInterval(()=>{socketUtil.reconnectMethod()},socketUtil.reconnectInterval)
    }
    wsClient.onmessage = ({ data }) => {
        console.log("收到服务端推送！")
        console.log(JSON.parse(data))

        useTestResultStore().addResult(JSON.parse(data))
    }
    wsClient.onerror = (()=>{
        console.log("error ")
        socketUtil.reconnectMethod()
    })
    socketUtil.wsClient = wsClient
}

socketUtil.reconnect = ()=>{
    if(lockReconnect){
        return;
    }
    lockReconnect = true;
    //没连接上会一直重连，设置延迟避免请求过多
    setTimeout(function () {
        console.log("ws 重连！")
        socketUtil.init()
        lockReconnect = false;
    }, 10000); //10秒后重连

}

socketUtil.reconnectMethod = ()=>{
    let msg = {text:"heartBeat"}
    console.log("发送心跳消息"+JSON.stringify(msg))
    Boolean(socketUtil.wsClient&&socketUtil.wsClient?.readyState!=1&&socketUtil.reconnect())||socketUtil.wsClient?.send(JSON.stringify(msg))

}

export default socketUtil
